﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace MiData
{
    public class MysqlMiDBAdapter : BaseDBAdapter
    {
        private MySqlConnection conn;
        public  DbConnection Connection
        {
            get
            {
               return this.conn;
            }
        }

        public MysqlMiDBAdapter(string db)
        {
            this.ConnectionString = db;
        }

        public  DbCommand CreateCommand(string sql)
        {
            DbCommand cmd = this.CreateCommand();
            cmd.CommandText = sql;
            return cmd;
        }

        public  DbCommand CreateCommand()
        {
            DbCommand cmd = new MySqlCommand();
            
            cmd.Connection = this.conn;

            return cmd;
        }

        public  DbDataReader QuickExecuteQuery(string sql)
        {
            return this.CreateCommand(sql).ExecuteReader();
        }

        public  int QuickExecuteNoQuery(string sql)
        {
            return this.CreateCommand(sql).ExecuteNonQuery();
        }

        private string connstr;
        public  string ConnectionString
        {
            get
            {
                return this.connstr;
            }
            set
            {
                this.connstr = value;
                if (this.conn != null) this.conn.Close();

                this.conn = new MySqlConnection(value);
            }
        }

        public  long GetLastInsertID()
        {
            string sql = "SELECT @@IDENTITY AS LID";
            long r = -1;

            DbDataReader reader = this.CreateCommand(sql).ExecuteReader();

            if (reader.Read())
            {
                r = reader.GetInt64(0);
            }
            reader.Close();
            return r;
        }


        public void Open()
        {
            this.conn.Open();
        }

        public void Close()
        {
            this.conn.Close();
        }
    }
}
